package com.aidex.biz.messageSend;

import com.aidex.biz.domain.JinjianInfo;
import com.aidex.biz.domain.MessageInfo;
import com.aidex.biz.domain.SmsLog;
import com.aidex.biz.service.SmsLogService;
import com.aidex.biz.service.impl.MessageInfoServiceImpl;
import com.aidex.biz.utils.TencentSmsUtils;
import com.aidex.common.core.domain.entity.Company;
import com.aidex.common.core.domain.entity.SysUser;
import com.aidex.common.core.redis.RedisCache;
import com.aidex.common.utils.StringUtils;
import com.aidex.framework.cache.ConfigUtils;
import com.aidex.system.domain.SysDictData;
import com.aidex.system.service.CompanyService;
import com.aidex.system.service.ISysUserService;
import com.aidex.system.service.SysDictDataService;
import com.aidex.wxCompany.WxWrokMessageService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class MessageSendServiceImpl implements MessageSendService {
    private static final Logger log = LoggerFactory.getLogger(MessageInfoServiceImpl.class);
    @Autowired
    RedisCache redisCache;
    @Autowired
    ISysUserService iSysUserService;

    /**
     * 企业微信消息
     */
    @Autowired
    WxWrokMessageService wxWrokMessageService;

    @Autowired
    CompanyService companyService;

    @Autowired
    SysDictDataService sysDictDataService;
    @Autowired
    private SmsLogService smsLogService;

    @Autowired
    private MessageSendService messageSendService;


    /**
     * 推送企业微信客户消息
     *
     * @param messageInfo
     */
    @Override
    public void sendMessageWxWork(MessageInfo messageInfo) {
        // 发送消息
        SysUser sysUser = iSysUserService.getUserCache(messageInfo.getUserId());
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
        String content = "时间：" + sdf.format(new Date()) + "\n" + "内容：" + messageInfo.getContent();
        System.out.print("发送号码：" + sysUser.getPhonenumber() + "\n" + content);
        //查询是否发送短信系统参数
        String sendSmsIsSend = ConfigUtils.getConfigValueByKey("sendWxms.isSend");
        if (StringUtils.isNotNull(sendSmsIsSend) && "是".equals(sendSmsIsSend)) {
            boolean isSelf = false;
            boolean isGroup = false;
            switch (messageInfo.getMsgType()) {
                case "0":
                    isSelf = true;
                    isGroup = true;
                    break;
                case "1":
                case "2":
                case "3":
                case "5":
                case "6":
                    isSelf = true;
                    break;
            }

            //1.发送消息给个人
            if (isSelf) {
                this.sendTextMessageByUser(new String[]{sysUser.getId()}, content);
            }
            //2.发送群消息@XX人
            Company company = companyService.getCompanyCache(sysUser.getCompanyId());
            if (StringUtils.isNotNull(company) && isGroup) {
                wxWrokMessageService.sendTxtMessageFromRobotToGroup(company.getLianxiAddress(), content, null,
                        new String[]{sysUser.getPhonenumber()});
            }
        }
    }

    @Override
    @Transactional(readOnly = false)
    public boolean sendTextMessageByUser(String[] userIds, String content) {
        List<SysUser> sysUserList = iSysUserService.findSendWxMsgUserListByIds(userIds);

        String[] userPinyinArray = sysUserList.stream().map(SysUser::getUserPinyin).toArray(String[]::new);
        Map<String, Object> resultMap = wxWrokMessageService.sendTextMessageByWxUserIds(userPinyinArray, content);
        //  Map<String, Object> resultMap = wxWrokMessageService.sendTextMessageByUser(phones, content);
        if (resultMap != null) {
            SmsLog smsLog = new SmsLog();
            smsLog.setReceiveId(resultMap.get("userId").toString());
            String[] phones = sysUserList.stream().map(SysUser::getPhonenumber).toArray(String[]::new);
            smsLog.setPhone(String.join(";", phones));
            smsLog.setStatus(resultMap.get("status").toString());
            smsLog.setRemark(resultMap.get("msg").toString());
            return smsLogService.save(smsLog);
        }
        return false;
    }


    /**
     * 批量推送企业微信私信消息
     *
     * @param messageInfoList
     */
    @Override
    public void sendMessageWxWorkToUserBatch(List<MessageInfo> messageInfoList) {
        // 发送消息
//        List<String> phoneList = new ArrayList<>();
//        for (MessageInfo messageInfo : messageInfoList) {
//            SysUser sysUser = iSysUserService.getUserCache(messageInfo.getUserId());
//            phoneList.add(sysUser.getPhonenumber());
//        }
//        String[] phones = phoneList.toArray(new String[0]);
        if (!messageInfoList.isEmpty()) {
            String[] userIds = messageInfoList.stream().map(MessageInfo::getUserId).toArray(String[]::new);
            MessageInfo messageInfo = messageInfoList.get(0);
            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
            String content = "时间：" + sdf.format(new Date()) + "\n" + "内容：" + messageInfo.getContent();
            //查询是否发送短信系统参数
            String sendSmsIsSend = ConfigUtils.getConfigValueByKey("sendWxms.isSend");
            if (StringUtils.isNotNull(sendSmsIsSend) && "是".equals(sendSmsIsSend)) {
                //1.发送消息给个人
                if (userIds.length > 0) {
                    this.sendTextMessageByUser(userIds, content);
                }
            }
        }

    }


    /**
     * 推送短信
     *
     * @param messageInfo
     */
    @Override
    public void sendShortMessage(MessageInfo messageInfo) {
        //查询是否发送短信系统参数
        String sendSmsIsSend = ConfigUtils.getConfigValueByKey("sendSms.isSend");
        if (StringUtils.isNotNull(sendSmsIsSend) && "是".equals(sendSmsIsSend)) {
            // 发送消息
            SysUser user = iSysUserService.getUserCache(messageInfo.getUserId());
            JSONObject jsonObject = JSONObject.parseObject(TencentSmsUtils.SmsSend(TencentSmsUtils.templateId_1,
                    messageInfo.getCusName(), user.getPhonenumber()));
            SmsLog smsLog = new SmsLog();
            smsLog.setPhone(user.getPhonenumber());
            smsLog.setReceiveId(user.getPhonenumber());
            smsLog.setCompanyId(user.getCompanyId());
            smsLog.setUserId(user.getUserId());
            smsLog.setUserName(user.getName());
            JSONArray jsonArray = jsonObject.getJSONArray("SendStatusSet");
            for (int i = 0; i < jsonArray.size(); i++) {
                smsLog.setStatus(jsonArray.getJSONObject(i).getString("Code"));
                smsLog.setRemark(jsonArray.getJSONObject(i).getString("Message"));
                smsLogService.save(smsLog);
            }
        }
    }

    /**
     * 企业微信群消息提醒
     *
     * @param robotAddress 群机器人地址
     * @param content      消息内容
     */
    @Override
    public void sendMessageWxWorkToGroup(String robotAddress, String content, String[] mobileList) {
        String sendSmsIsSend = ConfigUtils.getConfigValueByKey("sendWxms.isSend");
        if (StringUtils.isNotNull(sendSmsIsSend) && "是".equals(sendSmsIsSend)) {
            //给总公司发送群消息并艾特某个人
            if (StringUtils.isNotNull(robotAddress) && StringUtils.isNotNull(content)) {
                wxWrokMessageService.sendTxtMessageFromRobotToGroup(robotAddress, content, null, mobileList);
            }
        }
    }

    /**
     * 给总公司发送成交喜报并艾特某个人
     *
     * @param sysUser
     */
    @Override
    public void sendDealGoodNewsToRootCompany(SysUser sysUser, JinjianInfo jinjianInfo) {
        System.out.print("喜报推送");
        try {
            String sendSmsIsSend = ConfigUtils.getConfigValueByKey("sendWxms.isSend");
            if (StringUtils.isNotNull(sendSmsIsSend) && "是".equals(sendSmsIsSend) && null != jinjianInfo) {
                String productName = jinjianInfo.getProductName();
                BigDecimal fkAmount = jinjianInfo.getSjEdu();

                String sysDictDataLabel = sysDictDataService.selectDictLabel("org_type_options",
                        jinjianInfo.getOrgType());
                if (StringUtils.isNotNull(sysDictDataLabel)) {
                    if (sysDictDataLabel.contains("黑户")) {
                        productName = "";
                    }
                }
                if (StringUtils.isNull(productName)) {
                    productName = "";
                }

                // 不足3万用3万，小数往大取整
                if (null == fkAmount) {
                    fkAmount = BigDecimal.ZERO;
                }
                if (fkAmount.compareTo(new BigDecimal("30000")) < 0) {
                    fkAmount = new BigDecimal("30000");
                }
                //转成万元
                fkAmount = fkAmount.divide(new BigDecimal("10000"), 0, RoundingMode.CEILING //往大取整
                );

                String goodNewsModel = ConfigUtils.getConfigValueByKey("wxWork.deal.goodNews");
                if (StringUtils.isNotNull(goodNewsModel)) {
                    String content = String.format(goodNewsModel.replace("\\n", "\n"), sysUser.getName(), productName
                            , fkAmount);
                    String rootCompanyRobotAddress = ConfigUtils.getConfigValueByKey("tencent.wxWork.salesman");
                    this.sendMessageWxWorkToGroup(rootCompanyRobotAddress, content,
                            new String[]{sysUser.getPhonenumber()});
                }
            }
        } catch (Exception e) {
            log.error("调用sendDealGoodNewsToRootCompany错误：" + e.getMessage());
        }
    }

    @Override
    public void sendJinjianVxNewsToCompany(String[] mobileList, String dictValue, String[] params,
            String toHomeCompanyId) {
        try {
            Company company = companyService.get(toHomeCompanyId);
            if (StringUtils.isNull(mobileList) || StringUtils.isEmpty(mobileList)) {
                mobileList = new String[]{company.getLianxiPhone()};
            }
            this.sendVxNewsToCompany(mobileList, "jinjian_vx_msg", dictValue, params, company.getRemark());
        } catch (Exception e) {
            // throw new RuntimeException(e);
            log.error("sendJinjianVxNewsToCompany:{}", e.getLocalizedMessage());
        }
    }

    private void sendVxNewsToCompany(String[] mobileList, String dictType, String dictValue, String[] params,
            String robotAddress) {
        // 查找自定义的消息模板
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType(dictType);
        sysDictData.setDictValue(dictValue);
        List<SysDictData> list = sysDictDataService.findList(sysDictData);
        if (!CollectionUtils.isEmpty(list)) {
            String wxMsgModel = list.get(0).getRemark();
            if (StringUtils.isNotNull(wxMsgModel)) {
                String content = String.format(wxMsgModel.replace("\\n", "\n"), params);
//                if (null == sysUser) {
//                    sysUser = new SysUser();
//                    sysUser.setPhonenumber("@all");//艾特所有人
//                }
                messageSendService.sendMessageWxWorkToGroup(robotAddress, content, mobileList);
            }
        }
    }


}
